import { createApp } from "vue";
import { createRouter, createWebHistory } from "vue-router";
import App from "./App.vue";
import axios from './utils/api.js';
import dict from './utils/dict.js';
import Layui from '@layui/layui-vue';
import '@layui/layui-vue/lib/index.css';
import CryptoJS from 'crypto-js';

const app = createApp(App);

app.use(Layui);

app.config.globalProperties.$axios = axios;
app.config.globalProperties.$dict = dict;
app.config.globalProperties.$cryptoJS = CryptoJS;

import "./global.css";
import "./variable.css";

const routes = [
  {
    path: "/",
    name: "Index",
    component: () => import('./pages/Index.vue'),
    meta: {
      needLogin: true,
    }
  },
  {
    path: "/login",
    name: "Login",
    component: () => import('./pages/Login.vue'),
    meta: {
      needLogin: false,
    }
  },
  {
    path: "/findPsw",
    name: "FindPsw",
    component: () => import('./pages/FindPsw.vue'),
    meta: {
      needLogin: false,
    }
  },
  {
    path: "/register",
    name: "Register",
    component: () => import('./pages/Register.vue'),
    meta: {
      needLogin: false,
    }
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

router.beforeEach((toRoute, _, next) => {
  const metaTitle = toRoute?.meta?.title;
  const metaDesc = toRoute?.meta?.description;

  window.document.title = metaTitle || "福汇交易所";
  if (metaDesc) {
    addMetaTag(metaDesc);
  }

  let uKey = window.sessionStorage.getItem('uKey');
  if (toRoute.meta.needLogin) {
    if (uKey==1) {
      next();
    } else {
      next({ name: 'Login' });
    }
  } else {
    next();
  }
});

const addMetaTag = (value) => {
  const element = document.querySelector(`meta[name='description']`);
  if (element) {
    element.setAttribute("content", value);
  }
};

app.use(router).mount('#app');

export default router;
